import * as UserApi from '@/api/user'
import authority from '@/utils/authority'

const {
  token = '',
  name = '',
  avatar = '',
  introduction = '',
  menu = [],
  is_admin = false
} = authority.get() || {}

const user = {
  state: {
    token,
    name,
    avatar,
    introduction,
    is_admin,
    menu
  },

  mutations: {
    SET_USER: (state, payload) => {
      Object.entries(payload).forEach((key, value) => {
        state[key] = value
      })
    },
    SAVE_INFO: (state, payload) => {
      const { avatar, introduction, name, roles, token } = payload
      state.avatar = avatar
      state.introduction = introduction
      state.name = name
      state.roles = roles
      state.token = token
    }
  },

  actions: {
    // 登录
    login({ commit }, userInfo) {
      return UserApi.login({
        username: userInfo.username.trim(),
        password: userInfo.password
        // eslint-disable-next-line
      }).then((data) => {
        authority.set(data.admin)
        commit('SAVE_INFO', data.admin)
        commit('SET_PERMISSION_ROUTER')
      })
    },

    // 登出
    logout({ commit }) {
      return UserApi.logout().then(() => {
        commit('SET_USER', {
          token: ''
        })
        localStorage.clear()
      })
    }
  }
}

export default user
